<?php
/**
 * Created by PhpStorm.
 * User: tangbolong
 * Date: 2019/11/08
 * Time: 14:07
 */

/**
 * @apiVersion 1.0.0
 * @api {POST} /wechat/Weixin/bind 002微信授权OK
 * @apiDescription 微信授权
 * @apiGroup Wx
 * @apiPermission 公众号
 * @apiParam {string} type wurl微信授权
 * @apiParam {string} preurl 回调地址
 * @apiParamExample {json} 请求示例:
 * {
 *      "type": "wurl",
 *      "preurl": "http://wd.jujingame.com/userInfo",
 * }
 * @apiSuccess  {Int} code 状态
 * @apiSuccess  {Object} data 元数据
 * @apiSuccess  {String} msg 错误说明
 * @apiSuccessExample {json} 响应示例:
{

}

 * //操作未成功提示信息
 * {
 *      "code":0,
 *      "msg" :"错误说明"
 * }
 */
namespace app\wechat\controller;
use app\util\ReturnCode;
use app\wechat\common\logic\Codewx;
use app\wechat\common\logic\Authwx;
use think\Db;
use think\Exception;

class Weixin extends Base{

    private $testAppid='wx4087ec64331a9de3',$testSecret='4ee6ba93fb2c7ff9127b040ec5e436ef';

    //GET
    public function bind(){
        $domain = $_SERVER['HTTP_HOST'];
        $program_c = config('program');
        $config = $program_c[$domain];
        $appid = $config['AppID'];
        $secret = $config['AppSecret'];
        $ApiDomain = $config['ApiDomain'];
        $param= $this->request->get();
        if(!isset($param['type']))  return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少type参数');

        switch($param['type']){
            case 'wurl': //获取微信授权地址
//                var_dump(urlencode($param['preurl']));exit();
                $bname = $ApiDomain."/api/wechat/weixin/bind?preurl=".urlencode($param['preurl'])."&type=wxinfo";
                $rurl = urlencode($bname);
                $backUrl = Authwx::getUrl($appid,$rurl,'snsapi_userinfo');
//                var_dump($backUrl);exit();
                $this->redirect($backUrl);
//                header('Location:'.$backUrl);
                break;
            case'wxinfo'://微信强授权
                $code = $param['code'];
                try{
                    $access = Authwx::getAccess($appid,$secret,$code);
                    $wechatArray = Authwx::gUser($access['access_token'], $access['openid'], $access['scope']);
//                    var_dump($wechatArray);exit();

                    //回调url处理
                    $preurl = $param['preurl'];

                    $paramData = [
                        'openid' => $wechatArray['openid'],
                        'headimgurl' => urlencode($wechatArray['headimgurl']),
                        'nickname' => $wechatArray['nickname'],
                        'unionid' => isset($wechatArray['unionid'])?$wechatArray['unionid']:'',
                    ];
//                    $jumpUrl = convertUrlQuery($preurl,$paramData);
//                    $this->redirect($jumpUrl);
                    // 解析url，得到参数字符串
                    $arr = explode('?', $preurl);
                    $param_str = getUrlQuery($paramData);
                    if(count($arr)>1){
                        $jumpUrl = $preurl."&".$param_str;
                    }else{
                        $jumpUrl = $preurl."?".$param_str;
                    }
                    $this->redirect($jumpUrl);
                }catch(Exception $exception){
                    return json(['code'=>$exception->getCode(),'data'=>[],'msg'=>$exception->getMessage()]);
                }
                break;
            default :
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '授权失败');
        }
    }

    public function bindWithDraw(){
        $domain = $_SERVER['HTTP_HOST'];
        $config = config('program.'.$domain);
        $appid = $config['AppID'];
        $secret = $config['AppSecret'];
        $param= $this->request->get();
        if(!isset($param['type']))  return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少type参数');

        switch($param['type']){
            case 'wurl': //获取微信授权地址
//                var_dump(urlencode($param['preurl']));exit();
                $bname = config('wechat.www_url')."/wechat/weixin/bind?preurl=".urlencode($param['preurl'])."&type=wxinfo";
                $rurl = urlencode($bname);
//                var_dump($rurl);exit();
                $backUrl = Authwx::getUrl($appid,$rurl,'snsapi_userinfo');
//                var_dump($backUrl);exit();
                $this->redirect($backUrl);
//                header('Location:'.$backUrl);
                break;
            case'wxinfo'://微信强授权
                $code = $param['code'];
                try{
                    $access = Authwx::getAccess($appid,$secret,$code);
                    $wechatArray = Authwx::gUser($access['access_token'], $access['openid'], $access['scope']);
//                    var_dump($wechatArray);exit();

                    //回调url处理
                    $preurl = $param['preurl'];
                    $arr = parse_url($preurl);
//                    var_dump($arr);exit();

                    $paramData = [
                        'openid' => $wechatArray['openid'],
                        'headimgurl' => urlencode($wechatArray['headimgurl']),
                        'nickname' => $wechatArray['nickname'],
                        'unionid' => isset($wechatArray['unionid'])?$wechatArray['unionid']:'',
                    ];
                    $url = parse_url($preurl);
                    $param_str = convertUrlQuery($url['query']);
                    $paramData['depositID'] = $param_str['depositID'];
                    $param_str = getUrlQuery($paramData);
                    $arr = explode('?', $preurl);

                    $jumpUrl = $arr[0]."?".$param_str;
                    $this->redirect($jumpUrl);
                }catch(Exception $exception){
                    return json(['code'=>$exception->getCode(),'data'=>[],'msg'=>$exception->getMessage()]);
                }
                break;
            default :
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '授权失败');
        }
    }

}
